import { fitChartSize } from '../utils/tools';
import { chinaStationGeoCoordMap } from './coorDataSimple';
import { emptyIcon, offIcon, onIcon, tipBg } from './mapIcon';
import { fetchStationLocation } from './useFetchStationData';

export const provinceMapConfig = async ({
  provinceName,
  toolTipData,
  intl,
}: {
  provinceName: string;
  toolTipData: any[];
  intl: any;
}) => {
  const stationData = await fetchStationLocation();
  stationData.forEach((station) => {
    const { stationLongitude, stationLatitude, stationAddress } = station;
    chinaStationGeoCoordMap[stationAddress] = [stationLongitude, stationLatitude];
  });
  const convertData = (data: any[]) => {
    const res = [];
    for (let i = 0; i < data.length; i++) {
      const geoCoord = chinaStationGeoCoordMap[data[i].name];
      if (geoCoord) {
        res.push({
          name: data[i].name,
          value: geoCoord.concat(data[i].online ? 1 : 0), // 使用 1 表示在线，0 表示离线
          online: data[i].online,
        });
      }
    }
    return res;
  };

  const highlightChinaData = () => {
    const uniqueNames = new Set(); // 用于记录已添加的名称，防止重复添加
    return toolTipData
      .map((item: { name: string | number; online: any; count?: number }) => {
        if (uniqueNames.has(item.name)) {
          return null;
        }
        uniqueNames.add(item.name);
        const geoCoord = chinaStationGeoCoordMap[item.name];
        if (geoCoord) {
          return {
            name: item.name,
            value: geoCoord.concat(item.online ? 1 : 0), // 使用 1 表示在线，0 表示离线
            online: item.online,
            symbol: item.name === '中国' ? emptyIcon : item.online ? onIcon : offIcon,
            symbolSize:
              item.name === '中国'
                ? [fitChartSize(42), fitChartSize(48)]
                : [fitChartSize(42), fitChartSize(48)],
            symbolOffset: [0, -20],
            itemStyle: {
              normal: {
                color: item.online ? '#feb40e' : '#3ebbff',
                shadowBlur: false,
                shadowColor: false,
              },
              opacity: 1,
            },
            rippleEffect: {
              color: item.online ? '#feb40e' : '#3ebbff',
            },
          };
        } else {
          console.warn(`Geo coordinates not found for ${item.name}`);
          return null;
        }
      })
      .filter((item: null) => item !== null);
  };

  // 统计在线和离线站点数量
  let onlineCount: number = 0;
  let offlineCount: number = 0;
  toolTipData.forEach((item: any) => {
    if (item.online) {
      onlineCount++;
    } else {
      offlineCount++;
    }
  });

  let showTip: boolean;
  if (toolTipData.length >= 1) {
    showTip = true;
  } else {
    showTip = false;
  }

  return {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      triggerOn: 'mousemove',
      alwaysShowContent: false,
      backgroundColor: 'transparent',
      borderWidth: 0,
      padding: 0,
      formatter: function (params: { name: any }) {
        let toolTiphtml = '';
        for (let i = 0; i < toolTipData.length; i++) {
          if (params.name === toolTipData[i].name) {
            toolTiphtml = `<div style="width:240px;height:240px;background:url(${tipBg});background-size:100% 100%;overflow:hidden;" class="bgTip">
              <div style="width:100%;height:20px;line-height:40px;padding:0 20px">
                <i style="display:inline-block;width:8px;height:8px;border-radius:40px;"></i>
                <span style="margin-left:10px;color:#fff;font-size:16px;"></span>
              </div>
              <div style="padding:0px 20px">
                <p style="color:#73E7FB;font-size:14px;line-height: 18px; margin-bottom:10px;max-width: 170px; text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">
                ${toolTipData[i].stationName}</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.operationTime',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].date
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 15px; margin-bottom: 5px; display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.tenantName',
                })}:<span style="display:block;color:#C4D4F1;margin-left:3px;font-size:12px; max-width: 130px; text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">${
              toolTipData[i].tenant
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.ratedCapacity',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].capacity
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                 ${intl.formatMessage({
                   id: 'bigdata.ratedPower',
                 })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].power
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                 ${intl.formatMessage({
                   id: 'bigdata.zEfficiency',
                 })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].efficiency
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.cycleIndex',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].loop
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.integratedEfficiency',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].all
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.totalC',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].charge
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.totalDc',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].discharge
            }</span></p>
              </div>
            </div>`;
            break;
          }
        }
        return toolTiphtml;
      },
      show: showTip,
    },
    visualMap: {
      show: true,
      type: 'piecewise',
      pieces: [
        {
          value: 1,
          label: `${intl.formatMessage({ id: 'bigdata.online' })} (${onlineCount})`,
          color: '#feb40e',
        },
        {
          value: 0,
          label: `${intl.formatMessage({ id: 'bigdata.offline' })} (${offlineCount})`,
          color: '#3ebbff',
        },
      ],
      textStyle: {
        color: '#508FFF',
        fontSize: 12,
      },
      left: 0,
      bottom: 80,
      itemWidth: 20,
      itemHeight: 12,
      inRange: {
        opacity: 1, // 设置为可见
        color: ['#feb40e', '#feb40e'],
      },
      outOfRange: {
        symbol: 'none', // 设置为不可见
        opacity: '0',
        color: ['#3ebbff', '#feb40e'], // 设置为灰色
      },
    },
    geo: [
      {
        layoutCenter: ['50%', '50%'],
        layoutSize: '80%',
        show: true,
        map: provinceName,
        roam: true,
        zoom: 1,
        aspectScale: 0.75,
        center: undefined,
        label: {
          normal: {
            show: false,
            textStyle: {
              color: '#fff',
            },
          },
          emphasis: {
            show: true,
            textStyle: {
              color: '#fff',
            },
          },
        },
        itemStyle: {
          normal: {
            areaColor: {
              type: 'linear',
              x: 1200,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(3,27,78,0.75)',
                },
                {
                  offset: 1,
                  color: 'rgba(58,149,253,0.75)',
                },
              ],
              global: true,
            },
            borderColor: 'rgba(192, 243, 251,0.5)',
            borderWidth: 1,
            shadowOffsetY: 15,
            shadowBlur: 12,
          },
          emphasis: {
            areaColor: {
              type: 'linear',
              x: 1200,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(3,27,78,0.75)',
                },
                {
                  offset: 1,
                  color: 'rgba(58,149,253,0.75)',
                },
              ],
              global: true,
            },
          },
        },
      },
    ],
    series: [
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        geoIndex: 0,
        zlevel: 5,
        symbolSize: [32, 37],
        symbolOffset: [0, -20],
        data: highlightChinaData(),
      },
      {
        name: 'Top 5',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: convertData(toolTipData),
        showEffectOn: 'render',
        groupId: 'world-map-group', // 添加 groupId
        rippleEffect: {
          scale: 5,
          brushType: 'stroke',
        },
        label: {
          normal: {
            formatter: '{b}',
            position: 'bottom',
            show: false,
            color: '#fff',
            distance: 10,
          },
        },
        symbol: 'circle',
        symbolSize: [20, 10],
        itemStyle: {
          normal: {
            color: function (params: { data: { online: boolean } }) {
              return params.data.online ? '#feb40e' : '#3ebbff';
            },
            shadowBlur: 10,
            shadowColor: function (params: { data: { online: boolean } }) {
              return params.data.online ? '#feb40e' : '#3ebbff';
            },
          },
          opacity: 1,
        },
        zlevel: 4,
      },
    ],
  };
};
